<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use GaePlay\GoogleAuth;

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__ . '/views',
    'twig.options' => array(
        'cache' => false
    )
));

$app->register(new Silex\Provider\SessionServiceProvider());
$app['session.storage.handler'] = $app->share(function ($app)
{
    return new \google\appengine\ext\session\MemcacheSessionHandler();
});

$app['gapi.credentials.raw'] = file_get_contents(__DIR__ . '/../authconfig-gaeplay.json');
$app['gapi.credentials'] = json_decode($app['gapi.credentials.raw']);

$app->before(function (Request $request) use($app)
{
    if (! $app['session']->has('nonce')) {
        $app['session']->set('nonce', md5(mt_rand()));
    }

    $app['twig']->addGlobal('nonce', $app['session']->get('nonce'));
});

$app->get('/', function () use($app)
{
    $foo = new GoogleAuth();
    $app['session']->set('foo', 'bar');
    return 'Basic!';
});

$app->get('/signin', function () use($app)
{
    return $app['twig']->render('signin.html.twig', array(
        'clientId' => $app['gapi.credentials']->web->client_id
    ));
});

$app->get('/interactive-post', function () use($app)
{
    return $app['twig']->render('interactive-post.html.twig', array(
        'clientId' => $app['gapi.credentials']->web->client_id
    ));
});

$app->post('/gapi/postauth/{nonce}', function ($nonce, Request $request) use($app)
{
    if ($nonce !== $app['session']->get('nonce')) {
        return new Response('Invalid nonce', 401);
    }

    $app['session']->remove('nonce');

    $client = new Google_Client();
    $client->setAuthConfig($app['gapi.credentials.raw']);
    $client->setRedirectUri('postmessage');

    $accessToken = $client->authenticate($request->getContent());
    error_log('One-time code result:' . PHP_EOL . print_r(json_decode($accessToken), 1));

    return new Response('', 200);
});

return $app;
